package com.ncmmall.application.business.marketing;

import com.ncmmall.domain.business.goods.Goods;
import com.ncmmall.domain.business.goods.GoodsRepository;
import com.ncmmall.domain.business.goods.QGoods;
import com.ncmmall.domain.business.goods.sku.GoodsSku;
import com.ncmmall.domain.business.goods.sku.GoodsSkuRepository;
import com.ncmmall.domain.business.goods.sku.QGoodsSku;
import com.ncmmall.domain.business.marketing.seckill.QSeckillActivity;
import com.ncmmall.domain.business.marketing.seckill.QSeckillGoods;
import com.ncmmall.domain.business.marketing.seckill.QSeckillSession;
import com.ncmmall.domain.business.marketing.seckill.QSeckillSessionMerchantScope;
import com.ncmmall.domain.business.marketing.seckill.SeckillActivity;
import com.ncmmall.domain.business.marketing.seckill.SeckillActivityRepository;
import com.ncmmall.domain.business.marketing.seckill.SeckillGoods;
import com.ncmmall.domain.business.marketing.seckill.SeckillGoodsRepository;
import com.ncmmall.domain.business.marketing.seckill.SeckillSession;
import com.ncmmall.domain.business.marketing.seckill.SeckillSessionMerchantScope;
import com.ncmmall.domain.business.marketing.seckill.SeckillSessionMerchantScopeRepository;
import com.ncmmall.domain.business.marketing.seckill.SeckillSessionRepository;
import com.ncmmall.domain.security.user.QWebUser;
import com.ncmmall.domain.security.user.WebUser;
import com.ncmmall.querychannel.service.QueryChannelService;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableMap;
import com.google.common.primitives.Doubles;
import com.google.common.primitives.Ints;
import com.google.common.primitives.Longs;
import org.apache.commons.lang.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.List;

/**
 * @author linxs
 * @Description: 秒杀活动
 * @Date: 2020-02-12 09:49
 */
@Service
@Transactional
public class SeckillApplication {

    @Autowired
    private SeckillSessionMerchantScopeRepository seckillSessionMerchantScopeRepository;

    @Autowired
    private SeckillSessionRepository seckillSessionRepository;

    @Autowired
    private SeckillActivityRepository seckillActivityRepository;

    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private GoodsSkuRepository skuRepository;

    @Autowired
    private SeckillGoodsRepository seckillGoodsRepository;

    @Autowired
    private QueryChannelService queryChannelService;

    /**
     * 添加秒杀场次
     *
     * @param seckillSession
     */
    public void createSeckillSession(SeckillSession seckillSession) {

        seckillSession.setCreateTime(new Timestamp(System.currentTimeMillis()));
        seckillSession.setStatus(1);
        seckillSession.setIsValidity(1);
        seckillSessionRepository.save(seckillSession);

        List<String> ids = Splitter.on("-").omitEmptyStrings().trimResults().splitToList(seckillSession.getMerchantIdsData());
        for (String merchantId : ids) {
            SeckillSessionMerchantScope merchantScope = new SeckillSessionMerchantScope();
            merchantScope.setMerchant(queryChannelService.findOne(QWebUser.webUser.id.eq(Long.valueOf(merchantId)), WebUser.class));
            merchantScope.setSeckillSession(seckillSession);
            seckillSessionMerchantScopeRepository.save(merchantScope);
        }

    }


    /**
     * 下架
     *
     * @param id
     */
    public void soldOutSeckillSession(long id) {
        SeckillSession seckillSession = queryChannelService.findOne(QSeckillSession.seckillSession.id.eq(id), SeckillSession.class);
        seckillSession.setStatus(1);
        seckillSessionRepository.save(seckillSession);
    }

    /**
     * 上架
     *
     * @param id
     */
    public void putawaySeckillSession(long id) {
        SeckillSession seckillSession = queryChannelService.findOne(QSeckillSession.seckillSession.id.eq(id), SeckillSession.class);
        seckillSession.setStatus(2);
        seckillSessionRepository.save(seckillSession);
    }

    /**
     * 编辑
     *
     * @param params
     */
    public void modifySeckillSession(SeckillSession params) {

        SeckillSession seckillSession = queryChannelService.findOne(QSeckillSession.seckillSession.id.eq(params.getId()), SeckillSession.class);
        seckillSession.setName(params.getName());
        seckillSession.setApplyDeadline(params.getApplyDeadline());
        seckillSession.setMerchantScopeType(params.getMerchantScopeType());
        seckillSession.setSeckillBeginTime(params.getSeckillBeginTime());
        seckillSession.setSeckillEndTime(params.getSeckillEndTime());
        seckillSession.setSeckillTime(params.getSeckillTime());
        seckillSessionRepository.save(seckillSession);

        List<SeckillSessionMerchantScope> scopes = queryChannelService.findAll(QSeckillSessionMerchantScope.seckillSessionMerchantScope.seckillSession.eq(seckillSession), SeckillSessionMerchantScope.class);
        seckillSessionMerchantScopeRepository.delete(scopes);

        List<String> ids = Splitter.on("-").omitEmptyStrings().trimResults().splitToList(params.getMerchantIdsData());
        for (String merchantId : ids) {
            SeckillSessionMerchantScope merchantScope = new SeckillSessionMerchantScope();
            merchantScope.setMerchant(queryChannelService.findOne(QWebUser.webUser.id.eq(Long.valueOf(merchantId)), WebUser.class));
            merchantScope.setSeckillSession(seckillSession);
            seckillSessionMerchantScopeRepository.save(merchantScope);
        }

    }

    /**
     * 添加秒杀活动
     *
     * @param seckillActivity
     */
    public void createSeckillActivity(SeckillActivity seckillActivity) {
        seckillActivity.setStatus(1);
        seckillActivity.setIsValidity(1);
        seckillActivity.setCreateTime(new Timestamp(System.currentTimeMillis()));
        seckillActivityRepository.save(seckillActivity);

        int store = 0;
        List<String> skuesString = Splitter.on(";").trimResults().omitEmptyStrings().splitToList(seckillActivity.getSkuString());
        for (String item : skuesString) {
            GoodsSku sku = queryChannelService.findOne(QGoodsSku.goodsSku.id.eq(Long.valueOf(item.substring(0, item.indexOf(":")))), GoodsSku.class);
            int seckillStore = NumberUtils.toInt(item.substring(item.indexOf(":") + 1, item.indexOf("-")));
            double seckillPrice = NumberUtils.toDouble(item.substring(item.indexOf("-") + 1, item.lastIndexOf("-")));
            int seckillLimit = NumberUtils.toInt(item.substring(item.lastIndexOf("-") + 1));

            sku.setSeckillStore(seckillStore);
            sku.setSeckillPrice(seckillPrice);
            sku.setSeckillLimit(seckillLimit);
            skuRepository.save(sku);

            store += seckillStore;

        }

        List<String> goodsesString = Splitter.on(";").trimResults().omitEmptyStrings().splitToList(seckillActivity.getGoodsString());
        for (String item : goodsesString) {

            Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(Long.valueOf(item.substring(0, item.indexOf(":")))), Goods.class);
            goods.setSeckillPrice(NumberUtils.toDouble(item.substring(item.indexOf(":") + 1)));
            goods.setMarketingType(2);
            goods.setSeckillStatus(1);
            goods.setSeckillSession(seckillActivity.getSeckillSession());
            goods.setSeckillStore(store);
            goods.setSeckillSalesVolume(0);
            goodsRepository.save(goods);

            SeckillGoods seckillGoods = new SeckillGoods();
            seckillGoods.setGoods(goods);
            seckillGoods.setSeckillActivity(seckillActivity);

            seckillGoodsRepository.save(seckillGoods);
        }


        seckillActivity.setGoodsCount(goodsesString.size());
        seckillActivityRepository.save(seckillActivity);
    }


    /**
     * 编辑秒杀活动
     *
     * @param params
     */
    public void modifySeckillActivity(SeckillActivity params) {

        SeckillActivity seckillActivity = queryChannelService.findOne(QSeckillActivity.seckillActivity.id.eq(params.getId()), SeckillActivity.class);
        seckillActivity.setSeckillSession(params.getSeckillSession());
        seckillActivityRepository.save(seckillActivity);

        seckillGoodsRepository.delete(queryChannelService.findAll(QSeckillGoods.seckillGoods.seckillActivity.eq(seckillActivity), SeckillGoods.class));

        int store = 0;
        List<String> skuesString = Splitter.on(";").trimResults().omitEmptyStrings().splitToList(params.getSkuString());
        for (String item : skuesString) {
            GoodsSku sku = queryChannelService.findOne(QGoodsSku.goodsSku.id.eq(Longs.tryParse(item.substring(0, item.indexOf(":")))), GoodsSku.class);
            int seckillStore = Ints.tryParse(item.substring(item.indexOf(":") + 1, item.indexOf("-")));
            double seckillPrice = Doubles.tryParse(item.substring(item.indexOf("-") + 1, item.lastIndexOf("-")));
            int seckillLimit = Ints.tryParse(item.substring(item.lastIndexOf("-") + 1));

            sku.setSeckillStore(seckillStore);
            sku.setSeckillPrice(seckillPrice);
            sku.setSeckillLimit(seckillLimit);
            skuRepository.save(sku);

            store += seckillStore;
        }

        List<String> goodsesString = Splitter.on(";").trimResults().omitEmptyStrings().splitToList(params.getGoodsString());
        for (String item : goodsesString) {

            Goods goods = queryChannelService.findOne(QGoods.goods.id.eq(Longs.tryParse(item.substring(0, item.indexOf(":")))), Goods.class);
            goods.setSeckillPrice(Doubles.tryParse(item.substring(item.indexOf(":") + 1)));
            goods.setSeckillStore(store);
            goodsRepository.save(goods);

            SeckillGoods seckillGoods = new SeckillGoods();
            seckillGoods.setGoods(goods);
            seckillGoods.setSeckillActivity(seckillActivity);

            seckillGoodsRepository.save(seckillGoods);
        }

        seckillActivity.setGoodsCount(goodsesString.size());
        seckillActivityRepository.save(seckillActivity);
    }

    /**
     * 提交审核秒杀活动
     *
     * @param seckillActivity
     */
    public void applyProcessSeckillActivity(SeckillActivity seckillActivity) {
        seckillActivity.setStatus(2);
        seckillActivityRepository.save(seckillActivity);
    }

    /**
     * 审核秒杀活动
     */
    public void processSeckillActivity(SeckillActivity params) {
        SeckillActivity seckillActivity = queryChannelService.findOne(QSeckillActivity.seckillActivity.id.eq(params.getId()), SeckillActivity.class);
        seckillActivity.setStatus(params.getStatus());
        seckillActivity.setCheckNote(params.getCheckNote());
        seckillActivityRepository.save(seckillActivity);

        if (seckillActivity.getStatus() == 3) {
            List<Goods> goodses = queryChannelService.findAll("select s.goods from SeckillGoods s where s.seckillActivity.id  = :id ", ImmutableMap.of("id", seckillActivity.getId()), Goods.class);
            for (Goods goodse : goodses) {
                goodse.setSeckillStatus(seckillActivity.getStatus());
            }
        }

    }

    /**
     * 下架秒杀活动
     */
    public void soldoutSeckillActivity(SeckillActivity params) {

        SeckillActivity seckillActivity = queryChannelService.findOne(QSeckillActivity.seckillActivity.id.eq(params.getId()), SeckillActivity.class);
        seckillActivity.setStatus(5);
        seckillActivity.setIsValidity(1);
        seckillActivityRepository.save(seckillActivity);

        SeckillActivity activity = queryChannelService.findOne(QSeckillActivity.seckillActivity.id.eq(params.getId()), SeckillActivity.class);
        List<Goods> goodses = queryChannelService.findAll("select s.goods from SeckillGoods s where s.seckillActivity.id = :id ", ImmutableMap.of("id", activity.getId()), Goods.class);
        for (Goods goodse : goodses) {
            goodse.setSeckillStatus(7);
            goodsRepository.save(goodse);
        }
    }

    /**
     * 删除秒杀活动
     */
    public void removeSeckillActivity(SeckillActivity params) {

        SeckillActivity activity = queryChannelService.findOne(QSeckillActivity.seckillActivity.id.eq(params.getId()), SeckillActivity.class);

        List<Goods> goodses = queryChannelService.findAll("select s.goods from SeckillGoods s where s.seckillActivity.id = :id ", ImmutableMap.of("id", activity.getId()), Goods.class);
        for (Goods goodse : goodses) {
            goodse.setMarketingType(0);
            goodse.setSeckillSession(null);
            goodsRepository.save(goodse);
        }

        List<SeckillGoods> seckillGoodses = queryChannelService.findAll(QSeckillGoods.seckillGoods.seckillActivity.eq(activity), SeckillGoods.class);
        seckillGoodsRepository.delete(seckillGoodses);

        seckillActivityRepository.delete(activity);

    }

}
